#! /bin/bash
# 脚本名称: init_osd.sh
# 执行方式: init_osd.sh 数据盘盘符 日志盘盘符, EX: init_osd.sh dev4 dev3,其中dev4为新建osd的数据目录对应的磁盘, dev3为新建osd的日志目录对应的磁盘
# 执行位置: osd进程所在主机上运行
# 执行条件: 主机上面已安装ceph程序包, 并且有keyring可以和monitor相互通信
# 日期: 2016-08-13
# 版本: 0.2
# 脚本使用情况: 对于云主机该脚本能够正确进行osd初始化
# Define Paramers
MOUNT_OPTIONS='-t xfs -o rw,nodev,noexec,noatime,nodiratime,attr2,discard,inode64,logbsize=256k,noquota'
OSD_JOURNAL_SIZE=5120 # 用于定义osd日志盘的大小, 单位为MB

function judge_disk() { # 用于判定osd的数据目录对应的磁盘是否正在使用
  mount | grep "/dev/$1\b" &>> /dev/null
  if [[ $? == 0 ]];then
    echo "$1 has been mounted"
    exit 3
  fi
}

function get_disk_id() { ## 获取执行磁盘的标识wwn
  echo "########WWN#######" &>> /tmp/init_osd-${OSD_ID}.log
  ls -al /dev/disk/by-id/ | grep wwn | grep $1 &>> /tmp/init_osd-${OSD_ID}.log
  if [[ $? == 0 ]];then
    ls -la /dev/disk/by-id/ | grep wwn | grep $1 | awk '{print $9}' # 物理机情况下获取磁盘标识wwn, EX: wwn-0x55cd2e404c22fc96-part2
  else
    ls -la /dev/disk/by-id/ | grep $1 | awk '{print $9}' # 云主机情况下获取磁盘标识virtio, EX: virtio-f1fab406-708a-4e33-8-part2
  fi
}

function mount_disk() {
  systemctl status network.service &>> /dev/null
  if [[ $? == 0 ]];then
    echo "mount ${MOUNT_OPTIONS} /dev/disk/by-id/$1 /var/lib/ceph/osd/ceph-$2" >> /etc/rc.d/rc.local
  else
    echo "/dev/disk/by-id/$1 /var/lib/ceph/osd/ceph-$2 xfs rw,noexec,nodev,noatime,nodiratime,barrier=0,discard,inode64,logbsize=256k,delaylog 0 2" >> /etc/fstab
  fi
}

function init_osd() {
  judge_disk $1
  OSD_ID=$(ceph osd create)
  mkfs -t xfs -f -i size=2048 /dev/$1 &>> /tmp/init_osd-${OSD_ID}.log
  mkdir -pv /var/lib/ceph/osd/ceph-${OSD_ID} &>> /tmp/init_osd-${OSD_ID}.log
  mount ${MOUNT_OPTIONS} /dev/$1 /var/lib/ceph/osd/ceph-${OSD_ID} &>> /tmp/init_osd-${OSD_ID}.log
  DISK_ID=$(get_disk_id $1)
  JOURNAL_ID=$(get_disk_id $2)
  mount_disk ${DISK_ID} ${OSD_ID}
  echo -e "[osd.${OSD_ID}]\nhost = $(hostname)\nosd_data = /var/lib/ceph/osd/ceph-${OSD_ID}\nosd_journal_size = ${OSD_JOURNAL_SIZE}\nosd_journal = /dev/disk/by-id/${JOURNAL_ID}\n\n" >> /etc/ceph/ceph.conf
  OSD_UUID=$(lsblk -f | grep $1 | awk '{print $3}')
  ceph-osd -i ${OSD_ID} --mkfs --mkkey --osd-uuid ${OSD_UUID} &>> /tmp/init_osd-${OSD_ID}.log
  ceph auth add osd.${OSD_ID} osd 'allow *' mon 'allow rwx' -i /var/lib/ceph/osd/ceph-${OSD_ID}/keyring &>> /tmp/init_osd-${OSD_ID}.log
}

init_osd $1 $2
